package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.GfsReturnOrderService;
import com.winit.gfs.spi.command.CancelOrderCommand;
import com.winit.gfs.spi.command.GfsReturnOrderCreateCommand;
import com.winit.gfs.spi.command.GfsReturnOrderQueryCommand;
import com.winit.gfs.spi.vo.GfsResponseMsg;
import com.winit.gfs.spi.vo.GfsReturnOrderProductVo;
import com.winit.gfs.spi.vo.GfsReturnOrderVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * <Change to the actual description of this class>
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hou 	1.0  		2016-3-8 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/gfs/returnOrder")
public class GfsReturnOrderController extends BaseController {

    @Resource
    private GfsReturnOrderService gfsReturnOrderService;

    /**
     * 查询gfs订单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 校验参数
        this.validGfsOrderList(requestMsg);
        // 封装参数
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            GfsReturnOrderQueryCommand command = buildSearchCommand(json);

            Page<GfsReturnOrderVo> pageGfsOrders = gfsReturnOrderService.queryReturnOrderPage(command);

            Map<String, Object> data = getPageParams(pageGfsOrders);
            data.put("list", pageGfsOrders.getContent());
            // 返回结果参数
            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pageGfsOrders.getPageable().getPageNumber());
            pageMap.put("pageSize", pageGfsOrders.getPageable().getPageSize());
            pageMap.put("totalCount", pageGfsOrders.getTotalElements());
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    private GfsReturnOrderQueryCommand buildSearchCommand(JSONObject json) {
        GfsReturnOrderQueryCommand command = new GfsReturnOrderQueryCommand();
        command.setCtx(CommandContext.getContext());
        // 组装参数
        GfsReturnOrderVo orderVo = new GfsReturnOrderVo();
        // winit退货单号
        String winitOrderNo = json.getString("winitOrderNo");
        orderVo.setWinitOrderNo(winitOrderNo);
        // 退货单号
        String returnOrderNo = json.getString("returnOrderNo");
        orderVo.setReturnOrderNo(returnOrderNo);
        String sellerId = json.getString("sellerId");
        orderVo.setSellerId(sellerId);
        String buyerId = json.getString("buyerId");
        orderVo.setBuyerId(buyerId);
        String ebaySite = json.getString("ebaySite");
        orderVo.setReturnSite(ebaySite);
        String itemTitle = json.getString("itemTitle");
        orderVo.setItemName(itemTitle);
        String winitReturnNo = json.getString("winitReturnNo");
        orderVo.setWinitOrderNo(winitReturnNo);
        // 状态
        String status = json.getString("status");
        orderVo.setStatus(status);
        String refundDueDateFrom = json.getString("refundDueDateFrom");
        if (null != refundDueDateFrom) {
            refundDueDateFrom += " 00:00:00";
            Date from = DateUtil.parse2Date(refundDueDateFrom, DateUtil.FULL_DATE_STRING);
            command.setRefundDueDateFrom(from);
        }
        String refundDueDateTo = json.getString("refundDueDateTo");
        if (null != refundDueDateTo) {
            refundDueDateTo += " 00:00:00";
            Date to = DateUtil.parse2Date(refundDueDateTo, DateUtil.FULL_DATE_STRING);
            command.setRefundDueDateTo(to);
        }
        String refundDateFrom = json.getString("refundDateFrom");
        if (null != refundDateFrom) {
            refundDateFrom += " 00:00:00";
            Date from = DateUtil.parse2Date(refundDateFrom, DateUtil.FULL_DATE_STRING);
            command.setRefundDateFrom(from);
        }
        String refundDateTo = json.getString("refundDateTo");
        if (null != refundDateTo) {
            refundDateTo += " 00:00:00";
            Date to = DateUtil.parse2Date(refundDateTo, DateUtil.FULL_DATE_STRING);
            command.setRefundDateTo(to);
        }
        command.setOrderVo(orderVo);
        Searchable<?> searchable = buildSearchablePageParams(json);
        searchable.addSort(new Sort(Direction.DESC, "status"));
        String sort = json.getString("sort");
        String sortColumn = json.getString("sortColumn");
        // 排序方式
        Direction direction = Direction.DESC;
        if ("asc".equalsIgnoreCase(sort)) {
            direction = Direction.ASC;
        }
        if (StringUtils.isNotEmpty(sort) && StringUtils.isNotEmpty(sortColumn)) {
            searchable.addSort(new Sort(direction, sortColumn));
        }
        command.setSearchable(searchable);
        return command;
    }

    private void validGfsOrderList(RequestMsg requestMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            // JSONObject json = (JSONObject) obj;
            // 组装参数

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
    }

    /**
     * 创建退货订单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/createReturnOrder")
    public String createReturnOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validCreateReturnOrder(json);
            GfsReturnOrderCreateCommand command = new GfsReturnOrderCreateCommand();
            command.setCtx(CommandContext.getContext());
            command.setOrderType("RETURN");//退货
            //组装参数
            resolveReturnOrderData(json,command);
            String result = gfsReturnOrderService.createReturnOrder(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("winitOrderNo", result);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    private void resolveReturnOrderData(JSONObject json,GfsReturnOrderCreateCommand command) {
        if(null !=json.getString("isSubmit")){
            command.setSubmit("Y".equals(json.getString("isSubmit")) ? true : false);
        }else{
            command.setSubmit(false);
        }
        GfsReturnOrderVo returnOrderVo = new GfsReturnOrderVo();
        returnOrderVo.setId(json.getLong("id"));
        returnOrderVo.setWarehouseCode(json.getString("warehouseCode"));
        returnOrderVo.setWarehouseName(json.getString("warehouseName"));
        returnOrderVo.setTrackingNo(json.getString("winitReturnNo"));
        returnOrderVo.setWinitSkuCode(json.getString("winitSkuCode"));
        returnOrderVo.setReturnAddreessCode(json.getString("returnAddreessCode"));
        returnOrderVo.setReturnAddreessDetail(json.getString("returnAddreessDetail"));
        returnOrderVo.setWinitProductCode(json.getString("winitProductCode"));
        returnOrderVo.setMerchandiseSerno(json.getString("merchandiseSerno"));
        returnOrderVo.setLoginName(CommandContext.getContext().getUsername());
        returnOrderVo.setRemarks(json.getString("remarks"));
        returnOrderVo.setIsPhotograph(json.getString("isPhotograph"));
        JSONArray gfsOrderList = json.getJSONArray("productVos");
        List<GfsReturnOrderProductVo> productVos = new ArrayList<GfsReturnOrderProductVo>();
        for (Object object : gfsOrderList) {
            JSONObject jsonObject = (JSONObject) object;
            GfsReturnOrderProductVo productVo = new GfsReturnOrderProductVo();
            productVo.setProductCode(jsonObject.getString("productCode"));
            productVo.setDeclaredValue(jsonObject.getBigDecimal("declaredValue"));
            productVo.setHeight(jsonObject.getBigDecimal("height"));
            productVo.setLength(jsonObject.getBigDecimal("length"));
            productVo.setProductName(jsonObject.getString("productName"));
            productVo.setProductNameEn(jsonObject.getString("productNameEn"));
            productVo.setQuantity(jsonObject.getInteger("quantity"));
            productVo.setSpecification(jsonObject.getString("specification"));
            productVo.setWeight(jsonObject.getBigDecimal("weight"));
            productVo.setWidth(jsonObject.getBigDecimal("width"));
            returnOrderVo.setWinitSkuCode(jsonObject.getString("productCode"));
            productVos.add(productVo);
        }
        returnOrderVo.setProductVos(productVos);
        command.setReturnOrderVo(returnOrderVo);
    }
    
    private void validCreateReturnOrder(JSONObject json) {
        // winitReturnNo
        ValidateUtil.validNotNull(json, "winitReturnNo");
        // warehouseCode
        ValidateUtil.validNotNull(json, "warehouseCode");
       // winitProductCode
        ValidateUtil.validNotNull(json, "winitProductCode");
        // isSubmit
        ValidateUtil.validNotNull(json, "isSubmit");
        // returnAddreessCode
        //ValidateUtil.validNotNull(json, "returnAddreessCode");
        // returnAddreessDetail
        ValidateUtil.validNotNull(json, "returnAddreessDetail");
        if (!json.containsKey("productVos")) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "productVo");
        }
        JSONArray returnlist = json.getJSONArray("productVos");
        if (returnlist.size() <= 0) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "productVo");
        }
    }

    /**
     * 取消发货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancelOrder")
    public String cancelOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validateCancel(json);
            // 构建数据
            List<Long> listID = buildOrderIdList(json);
            CancelOrderCommand command = new CancelOrderCommand();
            command.setId(listID);
            command.setCtx(CommandContext.getContext());
            Long successCount = gfsReturnOrderService.cancelReturnOrderById(command);
            result.setSuccessNum(successCount.intValue());
            result.setFailNum((listID.size() - successCount.intValue()));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/queryReturnOrderById")
    public String queryReturnOrderById(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            if(!ValidateUtil.isNotNull(json, "id"))
            {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
            }
            GfsReturnOrderQueryCommand command = new GfsReturnOrderQueryCommand();
            command.setCtx(CommandContext.getContext());
            command.setId(json.getLong("id"));
            GfsReturnOrderVo orderVo = gfsReturnOrderService.queryReturnOrderById(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("returnOrder", orderVo);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    private void validateCancel(JSONObject json) {
        if (json.containsKey("gfsOrderList")) {
            JSONArray orderList = json.getJSONArray("gfsOrderList");
            for (Object obj : orderList) {
                JSONObject order = (JSONObject) obj;
                ValidateUtil.validNotNull(order, "gfsOrderId");
                ValidateUtil.valid(order, "gfsOrderId", 10, true);
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderList");
        }
    }

    private List<Long> buildOrderIdList(JSONObject json) {
        List<Long> listLong = new ArrayList<Long>();
        JSONArray orderList = json.getJSONArray("gfsOrderList");
        for (Object obj : orderList) {
            JSONObject orderID = (JSONObject) obj;
            if (orderID.containsKey("gfsOrderId")) {
                listLong.add(orderID.getLong("gfsOrderId"));
            }
        }
        return listLong;
    }
}
